<?php
/**
 * Created by PhpStorm.
 * User: Len
 * Date: 2018/12/5
 * Time: 12:55
 * Desc: 分配器
 */

namespace Library;

use Config\Main;

class Dispatch
{
    /**
     * @var array worker uid map
     * ------------------------------------------------------------
     */
    public static $zset_worker_uid_map_pool = [];

    /**
     * @var array 进程状态 worker 1 繁忙 其他 空闲
     * ------------------------------------------------------------
     */
    public static $worker_stats_pool = [];

    /**
     * @var array
     * ------------------------------------------------------------
     */
    public static $user_counter = [];


    /**
     * @param $worker_id
     * @param $uid_list
     * ------------------------------------------------------------
     */
    public static function destroy($worker_id, $uid_list)
    {
    }

    /**
     * uid 取模 分配 worker ID
     * @param string $data 请求包体
     * @return int
     * ------------------------------------------------------------
     */
    public static function mode($data)
    {
        // demo 可随意改动
        $worker_num = Main::$swooleSettins['worker_num'];
        $worker_id = rand(0, $worker_num - 1);

        // 请不要对未知参数进行丢包. 会出现异常错误
        if (strlen($data) > 10) {

            // 抓取 请求包体中 uid 参数
            preg_match("/\"uid\":(\d+)/i", $data, $response);
            $uid = $response[1] ?? 0;

            // 分配worker 进程

            // 调试可以输出 但 生产环境输出内存会大量溢出!!!

            // 最简单的逻辑 取模分配uid
            $worker_id = $uid % $worker_num;
        }

        return $worker_id;
    }


}